<?php

namespace App\Http\Controllers\Api;

use App\Events\OrderPaySuccess;
use App\Models\Group;
use App\Models\Order;
use App\Models\School;
use App\Models\Shop;
use App\Services\BaseService;
use App\Services\PayService;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 订单
 * Class OrderController
 * @package App\Http\Controllers\Api
 */
class OrderController extends Controller
{
    /**
     * 获取支付金额
     * 目前为2
     * 后期根据重量和距离计算
     */
    public function getPayPrice()
    {
        $this->success([
            'pay_price' => 2
        ]);
    }

    /**
     * 创建订单
     * @throws \Throwable
     */
    public function createOrder()
    {
        $payType = request()->input('pay_type', 'yue');
        $type = request()->input('type', 1);
        $shopId = request()->input('shop_id', 0);
        $schoolId = request()->input('school_id', 0);
        $toPic = request()->input('to_pic');
        if($shopId){
            $shop = Shop::whereKey($shopId)->first();
            $fromName = $shop->realname;
            $fromAddress = $shop->address;
            $fromPhone = $shop->phone;
        }else{
            $fromName = request()->input('from_name', '');
            $fromAddress = request()->input('from_address', '');
            $fromPhone = request()->input('from_phone', '');
        }
        if($schoolId){
            $school = School::whereKey($schoolId)->first();
            $toAddress = $school->address;
        }else{
            $toAddress = request()->input('to_address', '');
        }
        $unique = request()->input('unique', md5(time() . mt_rand(1, 1000000)));
        $payPrice = request()->input('pay_price', 2);

        $orderInfo = [
            'uid' => $this->uid,
            'unique' => $unique,
            'type' => $type,
            'from_shop_id' => $shopId,
            'order_id' =>  "LE".time().rand(100000,999999),
            'from_name' => $fromName,
            'from_phone' => $fromPhone,
            'from_address' =>  $fromAddress,
            'to_school_id' => $schoolId,
            'to_address' => $toAddress,
            'to_pic' => $toPic,
            'pay_price' => $payPrice,
            'pay_type' => $payType,
            'paid' => 0,
            'add_time' => time(),
            'status' => 0,
        ];
        DB::beginTransaction();
        try {
            //加order
            $order = new Order();
            $order->fill($orderInfo)->saveOrFail();
            //支付调用
            $payPrice = bcsub((float)$order['pay_price'], 0, 2);

            $payData = array(
                'body' => '',
                'subject' => '',
                'payType' => $payType,
                'orderId' => $order->order_id,
                'pay_price' => $payPrice,
                'payAttach' => 'legwork',
                'uid' => $this->uid
            );
            //统一支付中间方法
            $data = (new PayService())->pay($payData);
            if(isset($data['errorCode']) && $data['errorCode'] == -1 ){
                DB::rollback();
                return $this->error('-1',$data['message']);
            }
            DB::commit();
            return $this->success($data, '支付成功');
        }catch (\Exception $e){
            DB::rollback();
            $data = [
                'status' => 'PAY_ERROR',
                'result' => [],
            ];
            return $this->success($data, $e->getMessage());
        }
    }

    public function ticketInfo()
    {
        return $this->success([
            'price' => 1.5,
            'top_title' => '瓜瓜配送',
            'title' => '瓜瓜配送票务中心',
            'sub_title' => '线上付款,送票到店'
        ]);
    }

    /**
     * 支付订单
     * @throws \Throwable
     */
    public function payOrder()
    {
        $order_id = request()->input('order_id');
        $payType = request()->input('pay_type','weixin');
        $order = Order::where('order_id',$order_id)->where('uid',$this->uid)->first();
        //支付调用
        $payPrice = bcsub((float)$order['pay_price'], 0, 2);

        $payData = array(
            'body' => '',
            'subject' => '',
            'payType' => $payType,
            'orderId' => $order->order_id,
            'pay_price' => $payPrice,
            'payAttach' => 'legwork',
            'uid' => $this->uid
        );
        //统一支付中间方法
        $data = (new PayService())->pay($payData);

        if(isset($data['errorCode']) && $data['errorCode'] == -1 ){
            $this->error('-1',$data['message']);
        }
        $this->success($data, '支付成功');
    }

    /**
     * 买票
     * @throws \Throwable
     */
    public function payTicket()
    {
        $payType = request()->input('pay_type', 'weixin');
        $type = request()->input('type', 3);
        $remark = request()->input('remark', '');
        $unique = request()->input('unique', md5(time() . mt_rand(1, 1000000)));
        $price = request()->input('price', 1.5);
        $num = request()->input('num', 1);

        $toName = request()->input('to_name', '');
        $toAddress = request()->input('to_address', '');
        $toPhone = request()->input('to_phone', '');

        $payPrice = bcmul($price, $num ,2);
        if($payPrice <= 0){
            return $this->error('-1','支付失败，金额错误');
        }
        $orderInfo = [
            'uid' => $this->uid,
            'order_extend' => ['num' => $num, 'price' => $price],
            'unique' => $unique,
            'type' => $type,
            'from_shop_id' => 0,
            'order_id' =>  "LET".time().rand(100000,999999),
            'from_name' => '',
            'from_phone' => '',
            'from_address' =>  '',
            'to_school_id' => 0,
            'to_address' => $toAddress,
            'to_phone' => $toPhone,
            'to_name' => $toName,
            'to_pic' => '',
            'pay_price' => $payPrice,
            'pay_type' => $payType,
            'paid' => 0,
            'add_time' => time(),
            'status' => 0,
            'remark' => $remark
        ];
        DB::beginTransaction();
        try {
            //加order
            $order = new Order();
            $order->fill($orderInfo)->saveOrFail();
            //支付调用
            $payPrice = bcsub((float)$order['pay_price'], 0, 2);

            $payData = array(
                'body' => '',
                'subject' => '',
                'payType' => $payType,
                'orderId' => $order->order_id,
                'pay_price' => $payPrice,
                'payAttach' => 'ticket',
                'uid' => $this->uid
            );
            //统一支付中间方法
            $data = (new PayService())->pay($payData);
            if(isset($data['errorCode']) && $data['errorCode'] == -1 ){
                DB::rollback();
                return $this->error('-1',$data['message']);
            }
            DB::commit();
            return $this->success($data, '支付成功');
        }catch (\Exception $e){
            DB::rollback();
            $data = [
                'status' => 'PAY_ERROR',
                'result' => [],
            ];
            return $this->success($data, $e->getMessage());
        }
    }

    /**
     * 统一下单
     */
    public function unify()
    {
        $appId = request()->input('app_id');
        $sign = request()->input('sign');
        $group = Group::whereAppId($appId)->first();
        Log::info('统一下单：', request()->all());
        if(!$appId || !$group){
            return $this->error(-1, 'app_id错误');
        }

        if(md5($appId.$group->app_secret) != $sign){
            return $this->error(-1, '签名错误');
        }

        if($group->times != -1 && $group->times < 0){
            return $this->error(-1, '余额不足，请充值');
        }

        $exist = Order::whereOutTradeNo(request()->input('order_id'))->first();
        if($exist){
            return $this->success([
                'status' => 'SUCCESS',
                'result' => [],
            ], '订单已存在');
        }
        $school_name = request()->input('school_name');
        $school_info = School::where('name',$school_name)->first();
        if(empty($school_info)){
            $school_info =  new  School();
            $school_info->name = $school_name;
            $school_info->status = 1;
            $school_info->save();
        }
        $shop_name = request()->input('shop_name')."(".request()->input('shop_address').")";
        $shop_info = Shop::where('name',$shop_name)->first();
        if(empty($shop_info)){
            $shop_info = new Shop();
            $shop_info->name = $shop_name;
            $shop_info->status = 1;
            $shop_info->save();
        }
        $orderInfo = [
            'uid' => $appId,
            'group_id' => $group->id,
            'school_id' =>  $school_info->id,
            'shop_id' =>  $shop_info->id,
            'school_name' =>  $school_name,
            'type' => 10,
            'order_id' =>  "LE".time().rand(100000,999999),
            'from_name' => request()->input('shop_name'),
            'from_phone' => request()->input('shop_phone'),
            'from_address' =>  request()->input('shop_address'),
            'to_school_id' => $school_info->id,
            'to_address' => request()->input('user_address'),
            'to_phone' => request()->input('user_phone'),
            'to_name' => request()->input('user_name'),
            'to_pic' => '',
            'pay_price' => 0,
            'pay_type' => 'prepayment',
            'paid' => 1,
            'add_time' => time(),
            'status' => 1,
            'remark' => '',
            'out_trade_no' => request()->input('order_id'),
            'order_extend' => request()->input('order_extend')
        ];

        try {
            //加order
            $order = new Order();
            $order->fill($orderInfo)->saveOrFail();
            event(new OrderPaySuccess($order, 'legwork', 'prepayment'));
            DB::commit();
            return $this->success([
                'status' => 'SUCCESS',
                'result' => [],
            ], '下单成功');
        }catch (\Exception $e){
            DB::rollback();
            Log::error('统一下单错误：'.$e->getMessage().' app_id:'.$appId);
            $data = [
                'status' => 'ERROR',
                'result' => [],
            ];
            return $this->success($data, '下单错误');
        }
    }

    /**
     * 根据外部订单退单
     */
    public function refundByOutTradeNo()
    {
        $appId = request()->input('app_id');
        $sign = request()->input('sign');
        Log::info('统一退单处理：', request()->all());
        $group = Group::whereAppId($appId)->first();
        if(!$appId || !$group){
            return $this->error(-1, 'app_id错误');
        }

        if(md5($appId.$group->app_secret) != $sign){
            return $this->error(-1, '签名错误');
        }

        $orderId = request()->input('order_id');

        $order = Order::whereOutTradeNo($orderId)->first();
        if(!$order){
            return $this->error(-1, '订单号错误');
        }

        $order->status = -1; //取消订单
        $order->save();
        info('退单成功');

//        if($group && $group->times != -1){
//            $group->times += 1;
//            $group->save();
//        }

        return $this->success('', '退单成功');
    }
}
